package com.itheima.service;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class SpringSecurityUserService implements UserDetailsService {

    @Reference//使用dubbo远程调用用户服务
    private UserService userService;

    //根据用户名查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       //远程调用用户服务，根据用户名查询用户信息
        com.itheima.pojo.User user = userService.findByUsername(username);
        if (user == null) {
            //用户不存在
            return null;
        }
        //将用户信息返回给框架
        //框架会进行密码比对(页面提交的密码和数据库中查询的密码进行比对)
        List<GrantedAuthority> list = new ArrayList<>();
        Set<Role> roles = user.getRoles();

        for (Role role : roles) {
            //给当前登陆用户授予角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //给该角色授予相应权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        UserDetails userDetails = new User(username, user.getPassword(), list);

        return userDetails;

    }
}
